#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int is_letter(char ch)
{
	return ((ch>='a') &&(ch<='z'));
}

void bubble_sort(char **arr, int size)
{
	char *temp;
	for(int i=0;i<size;i++)
		for(int j=0;j<i;j++)
			if(strcmp(arr[j] ,arr[j+1])>0)
			{
				temp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = temp;
			}

}

int main(int argc, char *argv[])
{
	int num, flag, len, index, iindex;
	char ch;
	char *newname;
	FILE *fp;
	char **arr;
	if(argc < 3)
	{
		printf("usage: %s <filename> <num>\n", argv[0]);
		return 1;
	}
	num = atoi(argv[2]);
	arr = malloc(sizeof(char*) * num);
	newname = malloc(sizeof(char) * (strlen(argv[1]) + 5));
	sprintf(newname, "%s.txt", argv[1]);
	fp = fopen(argv[1], "rb");
	index = 0;
	do
	{
		flag = fread(&len,sizeof(int),1,fp);
		if(!flag) break;
		arr[index] = malloc(sizeof(char) * len);
		iindex = 0;
		for(int i=0;i<len;i++)
		{
			flag = fread(&ch, sizeof(char), 1, fp);
			if(is_letter(ch))
			{
				arr[index][iindex] = ch;
				iindex++;
			}
		}
		arr[index] = realloc(arr[index], sizeof(char)*iindex);
		index++;
	}while(flag);

	bubble_sort(arr, num);

	fclose(fp);
	fp = fopen(newname, "wt");



	for(int i=0;i<num;i++)
		fprintf(fp ,"%s\n", arr[i]);

	fclose(fp);
	return 0;
}
